package com.aiprompt.demos.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.aiprompt.demos.constant.UserConstant;
import com.aiprompt.demos.exception.BusinessException;
import com.aiprompt.demos.exception.ErrorCode;
import com.aiprompt.demos.exception.ThrowUtils;
import com.aiprompt.demos.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aiprompt.demos.model.domain.User;
import com.aiprompt.demos.model.dto.user.UserQueryRequest;
import com.aiprompt.demos.model.enums.UserRoleEnum;
import com.aiprompt.demos.model.vo.user.LoginUserVO;
import com.aiprompt.demos.model.vo.user.UserVO;
import com.aiprompt.demos.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-07-26 11:56:04
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    /**
     * 注册
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return  注册成功用户id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        // 2. 检查是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 3. 加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 4. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName("无名");
        user.setUserRole(UserConstant.DEFAULT_ROLE);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        return user.getId();
    }

    /**
     * 用户注册（完整版）
     */
    @Override
    public long userRegisterFull(String userAccount, String userPassword, String checkPassword,
                                String userName, String email, String phone, Integer gender, String registerSource) {
        // 1. 参数校验
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "必填参数不能为空");
        }

        // 账号格式校验
        if (userAccount.length() < 4 || userAccount.length() > 16) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号长度为4-16位");
        }
        if (!userAccount.matches("^[a-zA-Z0-9_]+$")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号只能包含字母、数字和下划线");
        }

        // 密码格式校验
        if (userPassword.length() < 8 || userPassword.length() > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度为8-20位");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }

        // 邮箱格式校验
        if (StrUtil.isNotBlank(email) && !email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式不正确");
        }

        // 手机号格式校验
        if (StrUtil.isNotBlank(phone) && !phone.matches("^1[3-9]\\d{9}$")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号格式不正确");
        }

        // 2. 检查账号是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已存在");
        }

        // 3. 检查邮箱是否重复
        if (StrUtil.isNotBlank(email)) {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("email", email);
            count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱已被注册");
            }
        }

        // 4. 检查手机号是否重复
        if (StrUtil.isNotBlank(phone)) {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号已被注册");
            }
        }

        // 5. 密码加密（使用BCrypt）
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encryptPassword = encoder.encode(userPassword);

        // 6. 创建用户对象
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName(StrUtil.isNotBlank(userName) ? userName : "用户" + userAccount);
        user.setEmail(email);
        user.setPhone(phone);
        user.setGender(gender != null ? gender : 0);
        user.setRegisterSource(StrUtil.isNotBlank(registerSource) ? registerSource : "web");
        user.setUserRole(UserConstant.DEFAULT_ROLE);
        user.setStatus(1); // 正常状态
        user.setLoginCount(0);

        // 7. 保存到数据库
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }

        log.info("用户注册成功，账号：{}, ID：{}", userAccount, user.getId());
        return user.getId();
    }

    /**
     * 登录
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request  保存登录态
     * @return  成功登录的用户脱敏实体
     */

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 参数校验
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号和密码不能为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号格式错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码格式错误");
        }

        // 2. 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("status", 1); // 只查询正常状态的用户
        User user = this.baseMapper.selectOne(queryWrapper);

        // 用户不存在
        if (user == null) {
            log.info("用户登录失败，账号不存在：{}", userAccount);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }

        // 3. 验证密码
        boolean passwordMatch = false;
        String storedPassword = user.getUserPassword();

        // 检查是否是BCrypt加密的密码
        if (storedPassword.startsWith("$2a$") || storedPassword.startsWith("$2b$") || storedPassword.startsWith("$2y$")) {
            // BCrypt加密密码验证
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            passwordMatch = encoder.matches(userPassword, storedPassword);
        } else {
            // 明文密码验证（临时支持，用于调试）
            passwordMatch = userPassword.equals(storedPassword);
            log.warn("用户 {} 使用明文密码登录，建议加密存储", userAccount);
        }

        if (!passwordMatch) {
            log.info("用户登录失败，密码错误：{}", userAccount);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }

        // 4. 更新登录信息
        user.setLastLoginTime(new Date());
        user.setLoginCount(user.getLoginCount() + 1);
        this.updateById(user);

        // 5. 记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);

        log.info("用户登录成功：{}", userAccount);
        return this.getLoginUserVO(user);
    }

    /**
     * 密码加密
     * @param userPassword  用户密码
     * @return 加密密码
     */
    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "gaoqiao";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    /**
     * 登录返回用户实体
     * @param user 需要脱敏返回的用户实体
     * @return  登录用户实体
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        // 不返回密码等敏感信息
        return loginUserVO;
    }

    /**
     * 获取当前登录的用户
     * @param request   登录态
     * @return  当前登录的用户实体
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        ThrowUtils.throwIf(currentUser == null || currentUser.getId() == null, ErrorCode.NOT_LOGIN_ERROR);
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        ThrowUtils.throwIf(currentUser == null, ErrorCode.NOT_LOGIN_ERROR);

        return currentUser;
    }

    /**
     * 用户登出
     * @param request  当前用户登录态
     * @return  成功失败
     */

    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 脱敏单个用户
     * @param user  需要脱敏的用户实体
     * @return 脱敏后的用户实体
     */
    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 批量脱敏用户
     * @param userList  需要脱敏的一组用户
     * @return 脱敏后的用户list
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    /**
     * 拼接查询字段
     * @param userQueryRequest  用户查询实体
     * @return 查询条件
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (userQueryRequest == null) {
            return queryWrapper;
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 是否为管理员
     * @param user  当前登录用户
     * @return 是否管理员
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.getAdminValue().equals(user.getUserRole());
    }

    /**
     * 更新用户个人信息
     */
    @Override
    public boolean updateUserProfile(Long userId, String userName, String userAvatar, String userProfile,
                                   String email, String phone, Integer gender, Date birthday) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID无效");
        }

        // 获取当前用户信息
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        // 检查邮箱是否被其他用户使用
        if (StrUtil.isNotBlank(email) && !email.equals(user.getEmail())) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("email", email);
            queryWrapper.ne("id", userId);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱已被其他用户使用");
            }
        }

        // 检查手机号是否被其他用户使用
        if (StrUtil.isNotBlank(phone) && !phone.equals(user.getPhone())) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            queryWrapper.ne("id", userId);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号已被其他用户使用");
            }
        }

        // 更新用户信息
        User updateUser = new User();
        updateUser.setId(userId);
        if (StrUtil.isNotBlank(userName)) {
            updateUser.setUserName(userName);
        }
        if (StrUtil.isNotBlank(userAvatar)) {
            updateUser.setUserAvatar(userAvatar);
        }
        if (StrUtil.isNotBlank(userProfile)) {
            updateUser.setUserProfile(userProfile);
        }
        if (StrUtil.isNotBlank(email)) {
            updateUser.setEmail(email);
        }
        if (StrUtil.isNotBlank(phone)) {
            updateUser.setPhone(phone);
        }
        if (gender != null) {
            updateUser.setGender(gender);
        }
        if (birthday != null) {
            updateUser.setBirthday(birthday);
        }
        updateUser.setEditTime(new Date());

        boolean result = this.updateById(updateUser);
        if (result) {
            log.info("用户信息更新成功，用户ID：{}", userId);
        }
        return result;
    }

    /**
     * 修改用户密码
     */
    @Override
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID无效");
        }

        if (StrUtil.hasBlank(oldPassword, newPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码不能为空");
        }

        if (newPassword.length() < 8 || newPassword.length() > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新密码长度为8-20位");
        }

        // 获取当前用户信息
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        // 验证原密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean passwordMatch = encoder.matches(oldPassword, user.getUserPassword());

        if (!passwordMatch) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "原密码错误");
        }

        // 检查新密码是否与原密码相同
        if (encoder.matches(newPassword, user.getUserPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新密码不能与原密码相同");
        }

        // 加密新密码
        String encryptedNewPassword = encoder.encode(newPassword);

        // 更新密码
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setUserPassword(encryptedNewPassword);
        updateUser.setEditTime(new Date());

        boolean result = this.updateById(updateUser);
        if (result) {
            log.info("用户密码修改成功，用户ID：{}", userId);
        }
        return result;
    }

}
